package com.artifex.mupdfdemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.Executor;

import org.w3c.dom.Document;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.SettingNotFoundException;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import com.rc.activity.R;
import com.rc.util.Const;

class ThreadPerTaskExecutor implements Executor {
	public void execute(Runnable r) {
		new Thread(r).start();
	}
}

public class MuPDFActivity extends Activity {
	public static final String DOCUMENT = "DOCUMENT";

	/* The core rendering instance */
	private MuPDFCore core;
	private String mFileName;
	private MuPDFReaderView mDocView;
	private View mButtonsView;
	private boolean mButtonsVisible;
	private EditText mPasswordView;
	private TextView mFilenameView;
	private SeekBar mPageSlider;
	private int mPageSliderRes;
	private TextView mPageNumberView;
	private TextView mInfoView;

	private ImageButton mSearchButton;
	/* private ImageButton mReflowButton; */
	/* private ImageButton mSelectButton; */
	/* private ImageButton mCancelSelectButton; */
	/* private ImageButton mCopySelectButton; */
	/* private ImageButton mStrikeOutButton; */
	/* private ImageButton mCancelButton; */

	/* private ImageButton mLinkButton; */
	private boolean mTopBarIsSearch;
	/* private ImageButton mSearchBack; */
	/* private ImageButton mSearchFwd; */
	private EditText mSearchText;
	private SearchTask mSearchTask;
	private AsyncTask<Void, Void, Integer> mMarkBookTask;
	private AsyncTask<Void, Void, Boolean> mMarkBookStateTask;
	private AsyncTask<Void, Void, List<List<String>>> mFullTextTask;

	// Mr-Dat
	private boolean mOutLineIsTOC = true;
	private boolean mOutLineIsOn;
	private ImageButton mCancelButton;
	private ImageButton mOutlineButton;
	private ViewAnimator mTopBarSwitcher;
	private Button mTocButton;
	private Button mMarkBookButton;
	private ImageButton mHomeButton;
	private RelativeLayout mSearchView;
	private RelativeLayout mTopBar;
	private ListView mListSearch;
	private ListView mListOutline;
	private Document mCurrentDocument;
	private ImageButton mMarkBook;
	private ImageButton mFilmMark;
	private ImageButton mDiagramMark;
	private ImageButton mQuizMark;
	private ImageButton mBrightness;
	private SeekBar mSeekBarBright;
	private boolean mBrightnessIsOn;

	private AlertDialog.Builder mAlertBuilder;
	/* private boolean mLinkHighlight = false; */
	private final Handler mHandler = new Handler();
	private boolean mAlertsActive = false;
	private boolean mReflow = false;
	private AsyncTask<Void, Void, MuPDFAlert> mAlertTask;
	private AlertDialog mAlertDialog;
	int brightness;
	private ContentResolver cResolver;
	private Window window;
	private String video;
	private String quiz;
	private List<List<String>> fullText;

	public void createAlertWaiter() {
		mAlertsActive = true;
		// All mupdf library calls are performed on asynchronous tasks to avoid
		// stalling
		// the UI. Some calls can lead to javascript-invoked requests to display
		// an
		// alert dialog and collect a reply from the user. The task has to be
		// blocked
		// until the user's reply is received. This method creates an
		// asynchronous task,
		// the purpose of which is to wait of these requests and produce the
		// dialog
		// in response, while leaving the core blocked. When the dialog receives
		// the
		// user's response, it is sent to the core via replyToAlert, unblocking
		// it.
		// Another alert-waiting task is then created to pick up the next alert.
		if (mAlertTask != null) {
			mAlertTask.cancel(true);
			mAlertTask = null;
		}
		if (mAlertDialog != null) {
			mAlertDialog.cancel();
			mAlertDialog = null;
		}
		mAlertTask = new AsyncTask<Void, Void, MuPDFAlert>() {

			@Override
			protected MuPDFAlert doInBackground(Void... arg0) {
				if (!mAlertsActive)
					return null;

				return core.waitForAlert();
			}

			@Override
			protected void onPostExecute(final MuPDFAlert result) {
				// core.waitForAlert may return null when shutting down
				if (result == null)
					return;
				final MuPDFAlert.ButtonPressed pressed[] = new MuPDFAlert.ButtonPressed[3];
				for (int i = 0; i < 3; i++)
					pressed[i] = MuPDFAlert.ButtonPressed.None;
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						mAlertDialog = null;
						if (mAlertsActive) {
							int index = 0;
							switch (which) {
							case AlertDialog.BUTTON1:
								index = 0;
								break;
							case AlertDialog.BUTTON2:
								index = 1;
								break;
							case AlertDialog.BUTTON3:
								index = 2;
								break;
							}
							result.buttonPressed = pressed[index];
							// Send the user's response to the core, so that it
							// can
							// continue processing.
							core.replyToAlert(result);
							// Create another alert-waiter to pick up the next
							// alert.
							createAlertWaiter();
						}
					}
				};
				mAlertDialog = mAlertBuilder.create();
				mAlertDialog.setTitle(result.title);
				mAlertDialog.setMessage(result.message);
				switch (result.iconType) {
				case Error:
					break;
				case Warning:
					break;
				case Question:
					break;
				case Status:
					break;
				}
				switch (result.buttonGroupType) {
				case OkCancel:
					mAlertDialog.setButton(AlertDialog.BUTTON2, "Cancel",
							listener);
					pressed[1] = MuPDFAlert.ButtonPressed.Cancel;
				case Ok:
					mAlertDialog.setButton(AlertDialog.BUTTON1, "Ok", listener);
					pressed[0] = MuPDFAlert.ButtonPressed.Ok;
					break;
				case YesNoCancel:
					mAlertDialog.setButton(AlertDialog.BUTTON3, "Cancel",
							listener);
					pressed[2] = MuPDFAlert.ButtonPressed.Cancel;
				case YesNo:
					mAlertDialog
							.setButton(AlertDialog.BUTTON1, "Yes", listener);
					pressed[0] = MuPDFAlert.ButtonPressed.Yes;
					mAlertDialog.setButton(AlertDialog.BUTTON2, "No", listener);
					pressed[1] = MuPDFAlert.ButtonPressed.No;
					break;
				}
				mAlertDialog
						.setOnCancelListener(new DialogInterface.OnCancelListener() {
							public void onCancel(DialogInterface dialog) {
								mAlertDialog = null;
								if (mAlertsActive) {
									result.buttonPressed = MuPDFAlert.ButtonPressed.None;
									core.replyToAlert(result);
									createAlertWaiter();
								}
							}
						});

				mAlertDialog.show();
			}
		};

		mAlertTask.executeOnExecutor(new ThreadPerTaskExecutor());
	}

	public void destroyAlertWaiter() {
		mAlertsActive = false;
		if (mAlertDialog != null) {
			mAlertDialog.cancel();
			mAlertDialog = null;
		}
		if (mAlertTask != null) {
			mAlertTask.cancel(true);
			mAlertTask = null;
		}
	}

	private MuPDFCore openFile(String path) {
		int lastSlashPos = path.lastIndexOf('/');
		mFileName = new String(lastSlashPos == -1 ? path
				: path.substring(lastSlashPos + 1));
		System.out.println("Trying to open " + path);
		try {
			core = new MuPDFCore(path);
			// New file: drop the old outline data
			OutlineActivityData.set(null);
		} catch (Exception e) {
			System.out.println(e);
			return null;
		}
		return core;
	}

	private MuPDFCore openBuffer(byte buffer[]) {
		System.out.println("Trying to open byte buffer");
		try {
			core = new MuPDFCore(buffer);
			// New file: drop the old outline data
			OutlineActivityData.set(null);
		} catch (Exception e) {
			System.out.println(e);
			return null;
		}
		return core;
	}

	String url = "";

	public static void callIntent(Context ct, String url) {
		Intent it = new Intent(ct, MuPDFActivity.class);
		it.putExtra("URL_PDF_FILE", url);
		ct.startActivity(it);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mAlertBuilder = new AlertDialog.Builder(this);

		if (core == null) {
			core = (MuPDFCore) getLastNonConfigurationInstance();
			if (savedInstanceState != null) {
				mCurrentDocument = (Document) savedInstanceState
						.getSerializable(DOCUMENT);
			}
			if (savedInstanceState != null
					&& savedInstanceState.containsKey("FileName")) {
				mFileName = savedInstanceState.getString("FileName");
			}
		}
		if (core == null) {
			Intent intent = getIntent();
			byte buffer[] = null;
			// if (Intent.ACTION_VIEW.equals(intent.getAction())) {
			Bundle bundle = intent.getExtras();
			Uri uri = null;
			if (bundle != null) {
				mCurrentDocument = (Document) bundle.getSerializable(DOCUMENT);
			} else {
				uri = intent.getData();
			}

			// String failString = null;
			// AssetManager assetManager = getBaseContext().getAssets();
			// try {
			// InputStream is = assetManager.open("intro.pdf");
			// int len = is.available();
			// buffer = new byte[len];
			// is.read(buffer, 0, len);
			// is.close();
			// } catch (java.lang.OutOfMemoryError e) {
			// System.out.println("Out of memory during buffer reading");
			// failString = e.toString();
			// } catch (Exception e) {
			// failString = e.toString();
			// }
			// if (failString != null) {
			// buffer = null;
			// Resources res = getResources();
			// AlertDialog alert = mAlertBuilder.create();
			// String contentFailure = res.getString(R.string.content_failure);
			// String openFailed = res.getString(R.string.open_failed);
			// setTitle(String.format(contentFailure, openFailed, failString));
			// alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
			// new DialogInterface.OnClickListener() {
			// public void onClick(DialogInterface dialog,
			// int which) {
			// finish();
			// }
			// });
			// alert.show();
			// return;
			// }

			if (getIntent().hasExtra("URL_PDF_FILE")) {
				url = Const.FILE_KEY
						+ getIntent().getStringExtra("URL_PDF_FILE");
			}
			File myFile = new File(url);
			FileInputStream fIn;
			try {
				fIn = new FileInputStream(myFile);
				int len = fIn.available();
				buffer = new byte[len];
				fIn.read(buffer, 0, len);
				fIn.close();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				Toast.makeText(MuPDFActivity.this,
						getString(R.string.loading_image), 1).show();
				finish();
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (buffer != null) {
				core = openBuffer(buffer);
			} else {
				core = openFile(Uri.decode(uri.getEncodedPath()));
			}
			SearchTaskResult.set(null);
			// }
			if (core != null && core.needsPassword()) {
				requestPassword(savedInstanceState);
				return;
			}
		}
		if (core == null) {
			AlertDialog alert = mAlertBuilder.create();
			alert.setTitle(R.string.open_failed);
			alert.setButton(AlertDialog.BUTTON_POSITIVE, "Dismiss",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			alert.show();
			return;
		}

		createUI(savedInstanceState);
	}

	public void requestPassword(final Bundle savedInstanceState) {
		mPasswordView = new EditText(this);
		mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
		mPasswordView
				.setTransformationMethod(new PasswordTransformationMethod());

		AlertDialog alert = mAlertBuilder.create();
		alert.setTitle(R.string.enter_password);
		alert.setView(mPasswordView);
		alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (core.authenticatePassword(mPasswordView.getText()
								.toString())) {
							createUI(savedInstanceState);
						} else {
							requestPassword(savedInstanceState);
						}
					}
				});
		alert.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
		alert.show();
	}

	public void createUI(Bundle savedInstanceState) {
		if (core == null)
			return;

		// Now create the UI.
		// First create the document view
		mDocView = new MuPDFReaderView(this) {
			@Override
			protected void onMoveToChild(int i) {
				if (core == null)
					return;
				mPageNumberView.setText(String.format("%d / %d", i + 1,
						core.countPages()));
				mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes);
				mPageSlider.setProgress(i * mPageSliderRes);
				super.onMoveToChild(i);
			}

			@Override
			protected void onTapMainDocArea() {
				if (!mButtonsVisible) {
				} else {
				}
			}

			@Override
			protected void onDocMotion() {
			}
		};

		mDocView.setAdapter(new MuPDFPageAdapter(this, core));

		// Make the buttons overlay, and store all its
		// controls in variables

		// Set up the page slider
		int smax = Math.max(core.countPages() - 1, 1);
		mPageSliderRes = ((10 + smax - 1) / smax) * 2;

		// Set the file-name text
		// mFilenameView.setText(mFileName);

		// Activate the seekbar
		if (mPageSlider != null) {

			mPageSlider
					.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
						public void onStopTrackingTouch(SeekBar seekBar) {
							mDocView.setDisplayedViewIndex((seekBar
									.getProgress() + mPageSliderRes / 2)
									/ mPageSliderRes);
						}

						public void onStartTrackingTouch(SeekBar seekBar) {
						}

						public void onProgressChanged(SeekBar seekBar,
								int progress, boolean fromUser) {
						}
					});

		}
		cResolver = getContentResolver();
		window = getWindow();
		if (mSeekBarBright != null) {
			mSeekBarBright.setMax(255);
			mSeekBarBright.setKeyProgressIncrement(1);

			try {
				// Get the current system brightness
				brightness = android.provider.Settings.System.getInt(cResolver,
						android.provider.Settings.System.SCREEN_BRIGHTNESS);
			} catch (SettingNotFoundException e) {
				// Throw an error case it couldn't be retrieved
				Log.e("Error", "Cannot access system brightness");
				e.printStackTrace();
			}
			mSeekBarBright.setProgress(brightness);
			mSeekBarBright
					.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

						@Override
						public void onStopTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub
							android.provider.Settings.System
									.putInt(cResolver,
											android.provider.Settings.System.SCREEN_BRIGHTNESS,
											brightness);
							android.view.WindowManager.LayoutParams layoutpars = (android.view.WindowManager.LayoutParams) window
									.getAttributes();
							// Set the brightness of this window
							layoutpars.screenBrightness = brightness
									/ (float) 255;
							// Apply attribute changes to this window
							window.setAttributes(layoutpars);
						}

						@Override
						public void onStartTrackingTouch(SeekBar seekBar) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProgressChanged(SeekBar seekBar,
								int progress, boolean fromUser) {
							// TODO Auto-generated method stub
							if (progress <= 20) {
								// Set the brightness to 20
								brightness = 20;
							} else // brightness is greater than 20
							{
								// Set brightness variable based on the progress
								// bar
								brightness = progress;
							}
						}
					});

			mBrightness.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					OutlineModeOff();
					searchModeOff();
				}
			});
		}
		// MrDat Activate the home button

		// Reenstate last state if it was recorded

		if (savedInstanceState == null
				|| !savedInstanceState.getBoolean("ButtonsHidden", false))

			if (savedInstanceState != null
					&& savedInstanceState.getBoolean("SearchMode", false))
				searchModeOn();

		// Stick the document view and the buttons overlay into a parent view
		RelativeLayout layout = new RelativeLayout(this);
		layout.addView(mDocView);
		layout.setBackgroundResource(R.drawable.tiled_background);
		// layout.setBackgroundResource(R.color.canvas);
		setContentView(layout);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode >= 0)
			mDocView.setDisplayedViewIndex(resultCode);
		super.onActivityResult(requestCode, resultCode, data);
	}

	public Object onRetainNonConfigurationInstance() {
		MuPDFCore mycore = core;
		core = null;
		return mycore;
	}

	private void toggleReflow() {
		mReflow = !mReflow;
		if (mReflow) {
			mDocView.setAdapter(new MuPDFReflowAdapter(this, core));
			/* mReflowButton.setColorFilter(Color.argb(0xFF, 172, 114, 37)); */
		} else {
			mDocView.setAdapter(new MuPDFPageAdapter(this, core));
			/* mReflowButton.setColorFilter(Color.argb(0xFF, 255, 255, 255)); */
		}
		mDocView.refresh(mReflow);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		if (mFileName != null && mDocView != null) {
			outState.putString("FileName", mFileName);

			// Store current page in the prefs against the file name,
			// so that we can pick it up each time the file is loaded
			// Other info is needed only for screen-orientation change,
			// so it can go in the bundle
			SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
			SharedPreferences.Editor edit = prefs.edit();
			edit.putInt("page" + mFileName, mDocView.getDisplayedViewIndex());
			edit.commit();
		}

		if (!mButtonsVisible)
			outState.putBoolean("ButtonsHidden", true);

		if (mTopBarIsSearch)
			outState.putBoolean("SearchMode", true);

		if (mCurrentDocument != null) {
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (mFileName != null && mDocView != null) {
			SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
			SharedPreferences.Editor edit = prefs.edit();
			edit.putInt("page" + mFileName, mDocView.getDisplayedViewIndex());
			edit.commit();
		}
	}

	public void onDestroy() {
		if (core != null)
			core.onDestroy();
		if (mAlertTask != null) {
			mAlertTask.cancel(true);
			mAlertTask = null;
		}
		core = null;
		super.onDestroy();
	}

	void searchModeOn() {
		if (!mTopBarIsSearch) {
			mTopBarIsSearch = true;
			// Focus on EditTextWidget
			mTopBarSwitcher.setDisplayedChild(0);
			Animation anim = new TranslateAnimation(0, 0,
					-mSearchView.getHeight(), 0);
			anim.setDuration(200);
			anim.setAnimationListener(new Animation.AnimationListener() {
				public void onAnimationStart(Animation animation) {
					mSearchView.setVisibility(View.VISIBLE);
				}

				public void onAnimationRepeat(Animation animation) {
				}

				public void onAnimationEnd(Animation animation) {
				}
			});
			mSearchView.startAnimation(anim);

			mSearchText.requestFocus();
			showKeyboard();
		} else {
			searchModeOff();
		}
	}

	void searchModeOff() {
		if (mTopBarIsSearch) {
			mTopBarIsSearch = false;
			hideKeyboard();
			// mTopBarSwitcher.setDisplayedChild(0);
			SearchTaskResult.set(null);
			// Make the ReaderView act on the change to mSearchTaskResult
			// via overridden onChildSetup method.
			mDocView.resetupChildren();
			Animation anim = new TranslateAnimation(0, 0, 0,
					-mSearchView.getHeight());
			anim.setDuration(200);
			anim.setAnimationListener(new Animation.AnimationListener() {
				public void onAnimationStart(Animation animation) {
				}

				public void onAnimationRepeat(Animation animation) {
				}

				public void onAnimationEnd(Animation animation) {
					mSearchView.setVisibility(View.INVISIBLE);
				}
			});
			mSearchView.startAnimation(anim);
		}
	}

	void outLineModeOn() {
		if (!mOutLineIsOn) {
			mOutLineIsOn = true;
			// Focus on EditTextWidget
			mTopBarSwitcher.setDisplayedChild(1);
			Animation anim = new TranslateAnimation(0, 0,
					-mSearchView.getHeight(), 0);
			anim.setDuration(200);
			anim.setAnimationListener(new Animation.AnimationListener() {
				public void onAnimationStart(Animation animation) {
					mSearchView.setVisibility(View.VISIBLE);
				}

				public void onAnimationRepeat(Animation animation) {
				}

				public void onAnimationEnd(Animation animation) {
				}
			});
			mSearchView.startAnimation(anim);
			hideKeyboard();
		}
	}

	void OutlineModeOff() {
		if (mOutLineIsOn) {
			mOutLineIsOn = false;
			// Make the ReaderView act on the change to mSearchTaskResult
			// via overridden onChildSetup method.
			Animation anim = new TranslateAnimation(0, 0, 0,
					-mSearchView.getHeight());
			anim.setDuration(200);
			anim.setAnimationListener(new Animation.AnimationListener() {
				public void onAnimationStart(Animation animation) {
				}

				public void onAnimationRepeat(Animation animation) {
				}

				public void onAnimationEnd(Animation animation) {
					mSearchView.setVisibility(View.INVISIBLE);
				}
			});
			mSearchView.startAnimation(anim);
		}
	}

	void showKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
			imm.showSoftInput(mSearchText, 0);
	}

	void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
			imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0);
	}

	void search(int direction) {
		hideKeyboard();
		int displayPage = mDocView.getDisplayedViewIndex();
		SearchTaskResult r = SearchTaskResult.get();
		int searchPage = r != null ? r.pageNumber : -1;
		mSearchTask.go(mSearchText.getText().toString(), direction,
				displayPage, searchPage);
	}

	@Override
	public boolean onSearchRequested() {
		if (mButtonsVisible && mTopBarIsSearch) {
		} else {
			searchModeOn();
		}
		return super.onSearchRequested();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (mButtonsVisible && !mTopBarIsSearch) {
		} else {
			searchModeOff();
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onStart() {
		if (core != null) {
			core.startAlerts();
			createAlertWaiter();
		}
		super.onStart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStop() {
		if (core != null) {
			destroyAlertWaiter();
			core.stopAlerts();
		}

		super.onStop();
	}

	@Override
	public void onBackPressed() {
		// if (core.hasChanges()) {
		// DialogInterface.OnClickListener listener = new
		// DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int which) {
		// if (which == AlertDialog.BUTTON_POSITIVE)
		// core.save();
		//
		// finish();
		// }
		// };
		// AlertDialog alert = mAlertBuilder.create();
		// alert.setTitle("MuPDF");
		// alert.setMessage("Document has changes. Save them?");
		// alert.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", listener);
		// alert.setButton(AlertDialog.BUTTON_NEGATIVE, "No", listener);
		// alert.show();
		// } else {
		// super.onBackPressed();
		// }
		super.onBackPressed();
		finish();
	}

}
